package com.bjsxt.shop.head.springmvc.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jboss.netty.handler.codec.http.HttpResponse;
import org.omg.CosNaming.NamingContextExtPackage.StringNameHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bjsxt.shop.common.controller.BaseController;
import com.bjsxt.shop.common.util.ConstatFinalUtil;
import com.bjsxt.shop.common.util.PageInfoUtil;
import com.bjsxt.shop.goods.pojo.AGoods;
import com.bjsxt.shop.goods.pojo.AGoodsCate;
import com.bjsxt.shop.goods.pojo.AGoodsEnum;
import com.bjsxt.shop.goods.pojo.AUsersCar;
import com.bjsxt.shop.goods.service.IGoodsService;
import com.bjsxt.shop.users.pojo.AUsers;

/**
 * 不需要登陆的Controller
 */
@Controller
public class IndexHeadController extends BaseController
{
	@Resource
	private IGoodsService goodsService;
	
	/**
	 * 首页
	 */
	@RequestMapping("/index")
	public String index()
	{
		ConstatFinalUtil.SYS_LOGGER.info("==main==");
		return "/head/index";
	}
	
	/**
	 * 商品分类列表
	 * @param cate 分类的url
	 */
	@RequestMapping("/cate_{cateUrl}")
	public String goodsCateList(@PathVariable String cateUrl,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("==goodsCateList==" + cateUrl);
		return this.goodsList(cateUrl, "1", model);
	}
	
	/**
	 * 商品分类列表
	 * @param cate 分类的url
	 * @return
	 */
	@RequestMapping("/goods_{cateUrl}_{currentPage}")
	public String goodsCatePageList(@PathVariable String cateUrl,@PathVariable String currentPage , Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("==goodsCatePageList==" + cateUrl);
		return this.goodsList(cateUrl, currentPage, model);
	}
	
	/**
	 * 重要性:
	 * 为什么要单独抽出一个goodsList方法
	 * 
	 * 不能让url直接访问
	 * @return
	 */
	private String goodsList(String cateUrl,String currentPage,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("==goodsList==" + cateUrl);
		/**
		 * 根据url中的分类的url取出分类的对象
			根据分类的id和启用的状态查商品
		 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("url", cateUrl);
		AGoodsCate goodsCate = this.goodsService.findOneGoodsCateService(condMap);
		
		/* 根据分类的Id和状态启用查询商品 */
		PageInfoUtil pageInfoUtil = this.proccedPageInfo(currentPage, "16");
		condMap.clear();
		if(goodsCate != null)
		{
			condMap.put("cateId", goodsCate.getId());
		}
		condMap.put("status", AGoodsEnum.STATUS_ENABLE.getStatus());
		Map<String, Object> resultMap = this.goodsService.findCondListGoodsService(pageInfoUtil, condMap);
		List<AGoods> goodsList = (List<AGoods>) resultMap.get("list");
		int totalRecord = Integer.valueOf(resultMap.get("totalRecord") + "");
		pageInfoUtil.setTotalRecord(totalRecord);
		/* 存储结果 */
		model.addAttribute("goodsCate", goodsCate);
		model.addAttribute("goodsList", goodsList);
		model.addAttribute("pageInfoUtil", pageInfoUtil);
		return "/head/goodsList";
	}
	
	/**
	 * 购物车列表页面展示
	 */
	
	@RequestMapping(value = "/usersCarInsertSubmit",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String usersCarInsertSubmit(HttpServletRequest request,HttpServletResponse response,String gid,String returnUrl){
		ConstatFinalUtil.SYS_LOGGER.info("-----购物车添加usersCarInsertSubmit------");
		if(gid == null)
		{
			gid = "" ; 
		}
		if(!"".equalsIgnoreCase(gid))
		{
			/* gid存在,
			 * gid:必须在数据库有才可以
			 *  */
			Map<String, Object> condMap = new HashMap<String, Object>();
			condMap.put("id", gid);
			AGoods goods = this.goodsService.findOneGoodsService(condMap);
			if(goods != null)
			{
				JSONArray goodsArr = new JSONArray() ;
				Cookie[] cookies = request.getCookies();
				for (int i = 0; i < cookies.length; i++)
				{
					Cookie cookie = cookies[i];
					if("goodsCarList".equalsIgnoreCase(cookie.getName()))
					{
						goodsArr = (JSONArray) JSON.parse(cookie.getValue()); 
					}
				}
				/* 一开始,假设不存在 */
				boolean flag = false ; 
				for (Iterator iterator = goodsArr.iterator(); iterator.hasNext();)
				{
					JSONObject goodsJSON = (JSONObject) iterator.next();
					if(gid.equalsIgnoreCase(goodsJSON.get("id") + ""))
					{
						/* 添加的商品已经存在 
						 * +1
						 * 原来的结果是1:
						 * 加完以后是否会出现:11 而不是2:
						 * Integer.valueOf(num) + 1 + "";2
						 * "" + Integer.valueOf(num) + 1 ;11
						 * */
						String num = goodsJSON.get("num") + "";
						goodsJSON.put("num", Integer.valueOf(num) + 1 + ""); 
						flag = true ; 
					}
				}
				
				/* 如何判断不存在的情况 */
				if(!flag)
				{
					JSONObject goodsJSON = new JSONObject() ; 
					goodsJSON.put("id", goods.getId() + "");
					goodsJSON.put("num", "1");
					
					goodsArr.add(goodsJSON);
				}
				
				ConstatFinalUtil.SYS_LOGGER.info("购物车结果:{}",goodsArr);
				/* 如何存储Cookie */
				Cookie cookie = new Cookie("goodsCarList", goodsArr.toJSONString());
				/* 设置 */
				cookie.setMaxAge(-1);
				cookie.setPath(request.getContextPath());
				
				/* 存储Cookie */
				response.addCookie(cookie);
				
				/* 成功 0*/
				info = ConstatFinalUtil.INFO_JSON.get("0") + "" ; 
			}else
			{
				/* 记录不存在 15*/
				info = ConstatFinalUtil.INFO_JSON.get("15") + "" ; 
			}
		}
		
		
		if(returnUrl == null)
		{
			returnUrl = "" ; 
		}
		StringBuffer sb = new StringBuffer() ;
		sb.append("<script type='text/javascript'>");
		sb.append("		alert('"+ info +"');");
		if(!"".equalsIgnoreCase(returnUrl))
		{
			/* 想跳转到原来的页面 */
			sb.append("		window.location.href = '" + returnUrl + "';");
		}else
		{
			sb.append("		window.location.href = '"+ request.getContextPath() +"';");
		}
		sb.append("</script>");
		/* return返回啥? */
		return sb.toString() ; 
	}
	
	@RequestMapping("/usersCarList")
	public String usersCarList(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--usersCarList--");
		
		
		//登录之后从数据库取数据，登录之前从cookie取数据
		HttpSession session = request.getSession() ; 
		AUsers users = (AUsers) session.getAttribute("users");
		
		/* 定义购物车数据 */
		List<AUsersCar> usersCarList = Collections.emptyList() ; 
		if(users != null)
		{
			usersCarList = usersCarListDb(users);
		}else
		{
			usersCarList = usersCarListCookie(request);
		}
		
		
		/* 页面跳转
		 * 页面循环usersCar
		 *  */
		model.addAttribute("usersCarList", usersCarList);
		return "/head/usersCarList" ; 
	}
	/*从数据库中取数据*/
	private List<AUsersCar> usersCarListDb(AUsers users){
		//根据用户的id和状态从数据库中取获取数据
		Map<String, Object>condMap=new HashMap<String,Object>();
		condMap.put("usersId",users.getId() );
		condMap.put("status", "1");
		Map<String, Object> resutlMap = this.goodsService.findCondListUsersCarService(null, condMap);
		List<AUsersCar> usersCarList = (List<AUsersCar>) resutlMap.get("list");
	
		return usersCarList ;
	}
	
	/*从cookie中取数据*/
	private List<AUsersCar> usersCarListCookie(HttpServletRequest request) {
		JSONArray goodsArr = new JSONArray() ;
		/* 
		 * 商品不能每次都new出来
		 *  */
		Cookie[] cookies = request.getCookies();
		for (int i = 0; i < cookies.length; i++)
		{
			Cookie cookie = cookies[i];
			if("goodsCarList".equalsIgnoreCase(cookie.getName()))
			{
				goodsArr = (JSONArray) JSON.parse(cookie.getValue()); 
			}
		}
		
		List<AUsersCar> usersCarList = new ArrayList<AUsersCar>();
		Map<String, Object> condMap = new HashMap<String, Object>();
		/* 循环,取到gid查询数据库 */
		for (Iterator iterator = goodsArr.iterator(); iterator.hasNext();)
		{
			JSONObject goodsJSON = (JSONObject) iterator.next();
			String gid = goodsJSON.get("id") + "";
			condMap.clear();
			condMap.put("id", gid);
			AGoods goods = this.goodsService.findOneGoodsService(condMap);
			
			String num = goodsJSON.get("num") + "";
			
			/* 购物车 */
			AUsersCar usersCar = new AUsersCar() ; 
			usersCar.setGoodsId(goods.getId());
			usersCar.setGoods(goods);;
			usersCar.setNum(Integer.valueOf(num));
			usersCarList.add(usersCar);
		}
		
		/*
		 * usersCarList:倒序
			for (int i = goodsArr.size() - 1; i >= 0; i--)
			{
				
			}
		 * */
		Collections.reverse(usersCarList);
		return usersCarList;
	}
}
